package org.i1510.common.utils.quartz;

import org.apache.commons.betwixt.io.BeanReader;
import org.i1510.common.bean.JobBean;
import org.i1510.common.bean.SpringQuartzBean;
import org.i1510.common.bean.SpringQuartzPropertyBean;
import org.quartz.CronTrigger;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QuartzHandler {

	private static final Logger logger = LoggerFactory
			.getLogger(QuartzHandler.class);

	private Scheduler scheduler;

	public QuartzHandler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}

	public QuartzHandler() {
		super();
	}

	/**
	*@Author 加载spring-quartz.xml 的规则
	*@Desc：
	*@param bean读取对象
	*@Version  QuartzHandler.java,v 1.1 2013-10-10 上午11:08:48 
	*/
	public void loadSpringQuartzXmlRules(BeanReader d){
		 // 当遇到<person>时，创建类Person的一个实例，并将其压入栈顶
		  d.addObjectCreate("beans/bean", SpringQuartzBean.class);
		  //修改标签 person 的属性class对应类属性classStr
		  d.addSetProperties("beans/bean", "class", "classStr");
		  
		  d.addSetProperties("beans/bean");
		  d.addSetNext("beans/bean", "addBean");

		  
		  d.addObjectCreate("beans/bean/property", SpringQuartzPropertyBean.class);
		  d.addSetNext("beans/bean/property", "addProperty");
		  d.addSetProperties("beans/bean/property");
		  
		  d.addCallMethod("beans/bean/property/value", "setValue", 0);
		  
		  d.addCallMethod("beans/bean/property/ref", "addRef", 1);
		  d.addCallParam("beans/bean/property/ref", 0, "bean");		
	}
	
	/**
	 * @Author Rambo
	 * @Desc： 计划暂停
	 * @Version QuartzHandler.java,v 1.1 2013-10-8 上午11:34:10
	 */
	public void standBy() {
		try {
			scheduler.standby();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @Author Rambo
	 * @Desc： 计划启动
	 * @Version QuartzHandler.java,v 1.1 2013-10-8 上午11:34:25
	 */
	public void start() {
		try {
			scheduler.start();
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}


	/**
	*@Author Rambo
	*@Desc：发布（增加）任务 <br/>已删除的方法 不允许执行
	*@param model  
	*@param dataMap 
	*@Version  QuartzHandler.java,v 1.1 2013-10-8 上午11:34:41 
	*/
	@Deprecated
	public void deploy(JobBean model, JobDataMap dataMap) {
//		JobDetail jobDetail = new JobDetail(model.getJobName(),
//				model.getGroup(), model.getJobClass());
//		jobDetail.setJobDataMap(dataMap);
//		try {
//			scheduler.scheduleJob(jobDetail, model.getTrigger());
//		} catch (SchedulerException e) {
//			e.printStackTrace();
//		}
	}


	/**
	*@Author Rambo
	*@Desc：卸载（删除）任务
	*@param jobName 任务
	*@param group  组
	*@Version  QuartzHandler.java,v 1.1 2013-10-8 上午11:34:55 
	*/
	public void unDeploy(String jobName, String group) {
		if (jobName.equals("") || group.equals("")) {
			return;
		}
		try {
			scheduler.deleteJob(jobName, group);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}
	
	/**
	*@Author Rambo
	*@Desc：暂停任务
	*@param jobName
	*@param group TODO
	*@Version  QuartzHandler.java,v 1.1 2013-10-8 上午11:51:23 
	*/
	public void pause(String jobName, String group) {
		if (jobName.equals("") || group.equals("")) {
			return;
		}
		try {
			scheduler.pauseJob(jobName, group);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}
	/**
	*@Author Rambo
	*@Desc：重启任务
	*@param jobName
	*@param group TODO
	*@Version  QuartzHandler.java,v 1.1 2013-10-8 上午11:52:47 
	*/
	public void resume(String jobName, String group) {
		if (jobName.equals("") || group.equals("")) {
			return;
		}
		try {
			scheduler.resumeJob(jobName, group);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}
	/**
	 * 更新定时任务的触发表达式
	 * 
	 * @param triggerName
	 *            触发器名字
	 * @param groupName
	 *            触发器组名字
	 * @param cronExpression
	 *            触发表达式
	 * @return 成功则返回true，否则返回false
	 */
	public boolean updateCronExpression(String triggerName, String groupName,
			String cronExpression) {
		try {
			CronTrigger trigger = (CronTrigger) getTrigger(triggerName,
					groupName);
			if (trigger == null) {
				return false;
			}
			if (trigger.getCronExpression().equals(cronExpression)) {
				logger.info("cronExpression is same with the running Schedule , no need to update.");
				return true;
			}
			trigger.setCronExpression(cronExpression);
			scheduler.rescheduleJob(trigger.getName(), trigger.getGroup(),
					trigger);
			logger.info("Update the cronExpression successfully!!");
			return true;
		} catch (SchedulerException e) {
			logger.error("Fail to reschedule. " + e);
			return false;
		} catch (java.text.ParseException e) {
			logger.error("The new cronExpression - " + cronExpression
					+ " not conform to the standard. " + e);
			return false;
		}
	}

	/**
	 * 获取触发器
	 * 
	 * @param triggerName
	 *            触发器名字
	 * @param groupName
	 *            触发器组名字
	 * @return 对应Trigger
	 */
	public Trigger getTrigger(String triggerName, String groupName) {
		Trigger trigger = null;
		if ("".equals(groupName)) {
			logger.warn("Schedule Job Group is empty!");
			return null;
		}
		if ("".equals(triggerName)) {
			logger.warn("Schedule trigger Name is empty!");
			return null;
		}
		try {
			trigger = scheduler.getTrigger(triggerName, groupName);
		} catch (SchedulerException e) {
			logger.warn("Fail to get the trigger (triggerName: " + triggerName
					+ ", groupName : " + groupName + ")");
			return null;
		}
		if (trigger == null) {
			logger.warn("Can not found the trigger of triggerName: "
					+ triggerName + ", groupName : " + groupName);
		}
		return trigger;
	}
}
